package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    //定义一个常量
    public final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * C端用户登录
     * @param dto
     * @return
     */
    @Override
    public Result<UserLoginVO> login(UserLoginDTO dto) {
        //1.调用微信登录凭证校验接口
            //1.2封装请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",dto.getCode());
        paramMap.put("grant_type","authorization_code");

        //1.1调用接口
        String body = HttpClientUtil.doGet(URL,paramMap);
            //1.3解析body字符串,然后获取openid
        Map map = JSON.parseObject(body, Map.class);
        String openid = (String)map.get("openid");
        log.info("微信用户返回的openid为：{}",openid);
            //1.4判断openid是否为空
        if(openid==null){
            return Result.error(MessageConstant.LOGIN_FAILED);
        }

        //2.判断当前用户是否是新用户，如果是则注册
            //2.1根据openid查询user表
        User user = userMapper.getByOpenId(openid);
        if (user == null) {
            //重新赋值给user
            user = user.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }

        //3.封装数据并返回数据
        String token = JwtUtil.getToken(user.getId());
        UserLoginVO vo = UserLoginVO.builder().id(user.getId()).openid(openid).token(token).build();
        return Result.success(vo);
    }
}
